package com.ecommerce.service;

import com.ecommerce.dao.InventoryDAO;
import com.ecommerce.dao.ProductDAO;
import com.ecommerce.model.InventoryHistory;
import com.ecommerce.model.Product;
import com.ecommerce.util.InputUtil;

import java.util.ArrayList;
import java.util.List;

public class InventoryService {
    private InventoryDAO inventoryDAO;
    private ProductDAO productDAO;
    private ProductService productService;

    public InventoryService() {
        this.inventoryDAO = new InventoryDAO();
        this.productDAO = new ProductDAO();
        this.productService = new ProductService();
    }

    public void displayLowStockProducts() {
        List<Product> lowStockProducts = productDAO.getLowStockProducts();

        System.out.println("\n=== 低库存商品预警 ===");
        if (lowStockProducts.isEmpty()) {
            System.out.println("暂无低库存商品");
        } else {
            System.out.println("以下商品库存不足，请及时补货:");
            for (Product product : lowStockProducts) {
                System.out.printf("商品: %s | 当前库存: %d | 阈值: %d | 状态: %s\n",
                        product.getName(), product.getStockQuantity(),
                        product.getLowStockThreshold(), product.getStockStatus());
            }
        }
        System.out.println("===================");
    }

    public void adjustStock(int userId) {
        System.out.println("\n=== 库存调整 ===");
        productService.displayAllProductsForAdmin();

        int productId = InputUtil.getIntInput("请输入要调整的商品ID: ");
        Product product = productDAO.getProductById(productId);

        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }

        System.out.println("当前库存信息:");
        System.out.println(product.toDetailedString());

        int newStock = InputUtil.getIntInput("请输入新的库存数量: ");
        String reason = InputUtil.getStringInput("请输入调整原因: ");

        if (newStock < 0) {
            System.out.println("库存数量不能为负数！");
            return;
        }

        boolean success = productDAO.updateProductStock(productId, newStock, "adjustment", reason, userId);
        if (success) {
            System.out.println("库存调整成功！");
        } else {
            System.out.println("库存调整失败！");
        }
    }

    public void purchaseStock(int userId) {
        System.out.println("\n=== 采购入库 ===");
        productService.displayAllProductsForAdmin();

        int productId = InputUtil.getIntInput("请输入要采购的商品ID: ");
        Product product = productDAO.getProductById(productId);

        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }

        System.out.println("当前库存: " + product.getStockQuantity());
        int purchaseQuantity = InputUtil.getIntInput("请输入采购数量: ");

        if (purchaseQuantity <= 0) {
            System.out.println("采购数量必须大于0！");
            return;
        }

        int newStock = product.getStockQuantity() + purchaseQuantity;
        String reason = InputUtil.getStringInput("请输入采购说明: ");

        // 直接计算新库存，避免在事务中查询
        boolean success = productDAO.updateProductStock(productId, newStock, "purchase", reason, userId);

        if (success) {
            System.out.println("采购入库成功！新库存: " + newStock);
        } else {
            System.out.println("采购入库失败！");
        }
    }

    public void viewInventoryHistory() {
        System.out.println("\n=== 查看库存历史 ===");
        System.out.println("1. 查看所有库存历史");
        System.out.println("2. 查看指定商品库存历史");

        int choice = InputUtil.getIntInput("请选择: ");

        switch (choice) {
            case 1:
                displayAllInventoryHistory();
                break;
            case 2:
                displayProductInventoryHistory();
                break;
            default:
                System.out.println("无效选择！");
        }
    }

    private void displayAllInventoryHistory() {
        List<InventoryHistory> history = inventoryDAO.getAllInventoryHistory();

        System.out.println("\n=== 所有库存变更历史 ===");
        if (history.isEmpty()) {
            System.out.println("暂无库存变更记录");
        } else {
            for (InventoryHistory record : history) {
                System.out.println(record);
            }
        }
        System.out.println("=====================");
    }

    private void displayProductInventoryHistory() {
        productService.displayAllProductsForAdmin();
        int productId = InputUtil.getIntInput("请输入商品ID: ");

        List<InventoryHistory> history = inventoryDAO.getInventoryHistoryByProduct(productId);
        Product product = productDAO.getProductById(productId);

        System.out.println("\n=== 商品库存历史: " + (product != null ? product.getName() : "未知") + " ===");
        if (history.isEmpty()) {
            System.out.println("该商品暂无库存变更记录");
        } else {
            for (InventoryHistory record : history) {
                System.out.println(record);
            }
        }
        System.out.println("=================================");
    }

    public void updateLowStockThreshold(int userId) {
        System.out.println("\n=== 更新低库存阈值 ===");
        productService.displayAllProductsForAdmin();

        int productId = InputUtil.getIntInput("请输入商品ID: ");
        Product product = productDAO.getProductById(productId);

        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }

        System.out.println("当前阈值: " + product.getLowStockThreshold());
        int newThreshold = InputUtil.getIntInput("请输入新的低库存阈值: ");

        if (newThreshold < 0) {
            System.out.println("阈值不能为负数！");
            return;
        }

        boolean success = inventoryDAO.updateLowStockThreshold(productId, newThreshold);
        if (success) {
            System.out.println("低库存阈值更新成功！");

            // 记录库存调整历史
            String reason = "更新低库存阈值为 " + newThreshold;
            productDAO.updateProductStock(productId, product.getStockQuantity(),
                    "adjustment", reason, userId);
        } else {
            System.out.println("低库存阈值更新失败！");
        }
    }

    public void displayStockReport() {
        List<Product> allProducts = productDAO.getAllProducts();
        List<Product> lowStockProducts = productDAO.getLowStockProducts();
        List<Product> outOfStockProducts = new ArrayList<>();

        for (Product product : allProducts) {
            if (product.getStockQuantity() == 0) {
                outOfStockProducts.add(product);
            }
        }

        System.out.println("\n=== 库存统计报告 ===");
        System.out.println("商品总数: " + allProducts.size());
        System.out.println("缺货商品: " + outOfStockProducts.size());
        System.out.println("低库存商品: " + lowStockProducts.size());
        System.out.println("库存充足商品: " + (allProducts.size() - outOfStockProducts.size() - lowStockProducts.size()));

        if (!outOfStockProducts.isEmpty()) {
            System.out.println("\n缺货商品列表:");
            for (Product product : outOfStockProducts) {
                System.out.println("  " + product.getName() + " (库存: 0)");
            }
        }

        if (!lowStockProducts.isEmpty()) {
            System.out.println("\n低库存商品列表:");
            for (Product product : lowStockProducts) {
                System.out.printf("  %s (库存: %d, 阈值: %d)\n",
                        product.getName(), product.getStockQuantity(),
                        product.getLowStockThreshold());
            }
        }
        System.out.println("===================");
    }

    public void manageInventory(int userId) {
        while (true) {
            System.out.println("\n=== 库存管理 ===");
            System.out.println("1. 查看库存统计");
            System.out.println("2. 低库存预警");
            System.out.println("3. 采购入库");
            System.out.println("4. 库存调整");
            System.out.println("5. 更新低库存阈值");
            System.out.println("6. 查看库存历史");
            System.out.println("7. 返回上级菜单");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    displayStockReport();
                    break;
                case 2:
                    displayLowStockProducts();
                    break;
                case 3:
                    purchaseStock(userId);
                    break;
                case 4:
                    adjustStock(userId);
                    break;
                case 5:
                    updateLowStockThreshold(userId);
                    break;
                case 6:
                    viewInventoryHistory();
                    break;
                case 7:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }
}